package com.woniuxy.secondkill.consumer;

import com.rabbitmq.client.Channel;
import com.woniuxy.secondkill.configuration.RabbitMQConfiguration;
import com.woniuxy.secondkill.utils.WebSocketUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author zhangyong
 * @Date 2021/8/13 0013上午 11:48
 */
@Component
public class KillConsumer {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = RabbitMQConfiguration.BUSINESS_QUEUE)
    public void consume(Message message, Channel channel) throws Exception {

        //为了看到死信消息，一进来就将消息变死信
//        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
//        return;
        //1.判断库存
        //1.1读取库存
        Integer num = (Integer) redisTemplate.opsForValue().get("num");

        if (num <= 0) {
            //秒杀结束
            //将消息队列里的消息拒绝
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,false);
            return;
        }

        //得到当前用户的账号
        String account = new String(message.getBody());

        //2.判断当前用户是否已经抢过
        if (redisTemplate.hasKey(account)) {
            //重复抢
            return;
        }

        //3.下单
        System.out.println(account + "用户抢到了" + num + "号商品");

        //减库存
        num--;
        redisTemplate.opsForValue().set("num", num);

        //记录当前用户秒杀成功
        redisTemplate.opsForValue().set(account, true);

        //在数据库生成订单信息

        //消费确认成功，让队列将消息从队列中移除   第二个参数是否批量删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        //返回结果：秒杀成功去付钱
        WebSocketUtil.send(account,"恭喜你抢购成功");


    }
}
